/**
 * 
 */
package com.idea.zd.sys.interceptor;

import java.util.Date;

import org.apache.log4j.Logger;

import com.idea.zd.sys.model.Admin;
import com.idea.zd.sys.model.Log;
import com.idea.zd.sys.service.LogService;
import com.idea.zd.sys.util.CommonUtils;
import com.jfinal.aop.Enhancer;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.server.ExceptionAdvisor;

/**
 * @author y.z
 * exception By Controller
 */
public class SysLogInterceptor implements Interceptor{
	private static final Logger logs = Logger.getLogger(SysLogInterceptor.class);
	private LogService logService = Enhancer.enhance(LogService.class);
	/* (non-Javadoc)
	 * @see com.jfinal.aop.Interceptor#intercept(com.jfinal.aop.Invocation)
	 */
	@Override
	public void intercept(Invocation inv) {
		Long startTime = System.currentTimeMillis();
		Admin admin = inv.getController().getSessionAttr("admin");
		Log log = new Log();
		if(null != admin){
			log.set("aid", admin.get("id"));
			log.set("admin_name", admin.get("name"));
		}
		log.set("from", inv.getController().getRequest().getHeader("Referer"));
		log.set("ip", CommonUtils.getIP(inv.getController().getRequest()));
		log.set("url", inv.getActionKey());
		log.set("date", new Date());
		log.set("class_name", inv.getController().getClass().getName());
		log.set("method_name", inv.getMethodName());
		log.set("start_time", new Date(startTime));
		log.set("err_code", 0);
		
		try{
			inv.invoke();
		}catch(Exception e){
			log.set("err_code", -1);
			log.set("err_msg", e.getMessage());
			throw e;
		}finally{
			log.set("spend_time", System.currentTimeMillis()-startTime);
			logService.save(log);
		}


	}

}
